package readini

import(
	"os"
	"io"
	"bufio"
	"fmt"
	"strings"
	"runtime"
)

var result map[string]string

//初始化
var ANNOTATION byte

func Init() {
	system_type := runtime.GOOS
	if system_type == "windows" {
		ANNOTATION  = ';'
	} else if system_type == "linux" {
		ANNOTATION = '#'
	}
}

//自定义错误
var e error;

type myerror struct{

	s string;
}
func (err myerror) Error() string{
	return err.s;
}

//listener接口
type Listener interface{
	listen(path string);
}
type listenfunc struct{

}
type ListenFunc func(string)


func (lis listenfunc) listen(path string){
	for {
		nowmap:=ReadFile(path);
		if e!=nil {return;}
		if (len(nowmap)!=len(result)){
			result=nowmap;
			fmt.Println("Change has happened.");
			return;
		}

		for i,s:=range nowmap{
			if s!=result[i]{

				result=nowmap;
				fmt.Println("Change has happened.");
				
				return;
			}
		}	
	}
}

func Watch(path string,listener Listener) (map[string]string,error){
	e=nil;
	result=ReadFile(path);

	if e!=nil{
		fmt.Println("",e.Error());
		return make(map[string]string),e;
	}

	fmt.Println("BEFORE:");
	for i,s:=range result{
		fmt.Printf("%s  :  %s\n",i,s);
	}
	if (listener==nil){
		listener=new (listenfunc);
	}
	listener.listen(path);

	if e!=nil{
		fmt.Println("",e.Error());
		return make(map[string]string),e
	}

	fmt.Println("AFTER:");
	for i,s:=range result{
		fmt.Printf("%s  :  %s\n",i,s);
	}
	

	return result,e;
}

func ReadFile(path string) map[string]string{
    file,err:=os.Open(path);
	if err!=nil{
		newerr:=new (myerror);
		newerr.s="Open Error!";
		e=newerr;
		nret:=make(map[string]string);
		return nret;
	}
	
	Init();
	reader:=bufio.NewReader(file);

	ansmap:=make(map[string]string);

	for {
		line,err:=reader.ReadString('\n');
		if err!=nil{
			if err==io.EOF{
				break;
			}
			newerr:=new (myerror);
			newerr.s="Read Error!";
			e=newerr;
			nret:=make(map[string]string);
			return nret;
		}
		line = strings.TrimSpace(line)
		if line == "" || line[0] == ANNOTATION || line[0] == '[' {
			continue
		}
		tmp := strings.Split(line, " = ")
		strings.Replace(tmp[1], "\\n", "", -1)
		ansmap[tmp[0]] = tmp[1]
	}

	return ansmap;
}